package com.huazhi.wzsnw.service.impl;

import com.huazhi.wzsnw.constant.CommonUser;
import com.huazhi.wzsnw.mapper.AlertMapper;
import com.huazhi.wzsnw.model.Alert;
import com.huazhi.wzsnw.model.User;
import com.huazhi.wzsnw.service.AlertService;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class AlertServiceImpl implements AlertService {
    @Autowired
    private AlertMapper alertMapper;

    @Override
    public List<String> getSearchAlertList(String search, Alert alert) {
        return alertMapper.getSearchAlertList(search, alert);
    }

    @Override
    public List<String> getSearchAlertListByRequest(HttpServletRequest request) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String search = request.getParameter("key");
        String selectdata = request.getParameter("selectdata");
        String start = request.getParameter("starttime");
        String end = request.getParameter("endtime");
        String category = request.getParameter("category");
        Alert alert = new Alert();
        List<String> list = new ArrayList<>();
        if(selectdata != null && !"".equals(selectdata)){
            String [] ids = selectdata.split(",");
            list = Arrays.asList(ids);
        }else {
            if(start != null && !"".equals(start)){
                alert.setStarttime(dateFormat.parse(start));
            }
            if(end != null && !"".equals(end)){
                alert.setEndtime(dateFormat.parse(end));
            }
            if(category != null && !"".equals(category)){
                alert.setCategory(category);
            }
            List<String> params = new ArrayList<String>();
            if (search == null) { search = ""; }
            if ("".equals(search)) {
                params.add("");
            } else if (search.contains(" ")) {
                params = Arrays.asList(search.split(" "));
            } else if (!search.contains(" ")) {
                params.add(search);
            }
            boolean firstSearch = true;
            for (String oneParam : params) {
                if (firstSearch) {
                    list = getSearchAlertList(oneParam,alert);
                    firstSearch = false;
                } else {
                    List<String> middleList = getSearchAlertList(oneParam,alert);
                    list.retainAll(middleList);
                }
            }
        }
        return list;
    }

    @Override
    public List<Alert> getAlertListByClassify(Alert alert,Integer pageIndex,Integer pageSize) {
        return alertMapper.getAlertListByClassify(alert, pageIndex, pageSize);
    }

    @Override
    public List<Alert> getClassifyByRequest(HttpServletRequest request, Integer pageIndex, Integer pageSize) throws ParseException {
        String starttime = request.getParameter("starttime");
        String endtime = request.getParameter("endtime");
        String category = request.getParameter("category");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Alert alert = new Alert();
        alert.setCategory(category);
        if(starttime != null && !"".equals(starttime)){
            alert.setStarttime(dateFormat.parse(starttime));
        }
        if(endtime != null && !"".equals(endtime)){
            alert.setEndtime(dateFormat.parse(endtime));
        }
        return alertMapper.getAlertListByClassify(alert,pageIndex,pageSize);
    }

    @Override
    public void ExportClassifyExcel(OutputStream out,List<Alert> alertList, String type) {
        try{
            String [] head = new String[0];
            switch (type) {
                case "异常信息表":
                    head = new String[]{"DTU编号", "异常类型", "异常原因", "发生时间", "所在经度", "所在纬度", "状态"};
                    break;
                case "异常汇总表":
                    head = new String[]{"DTU编号", "异常类型", "异常原因", "异常数量"};
                    break;
                case "异常DTU编号汇总表":
                    head = new String[]{"DTU编号", "异常数量"};
                    break;
                case "异常类型汇总表":
                    head = new String[]{"异常类型", "异常数量"};
                    break;
                case "异常原因汇总表":
                    head = new String[]{"异常原因", "异常数量"};
                    break;
                default:
                    break;
            }
            SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 创建excel文档,在工作簿构建时指定窗口大小
            Sheet sheet = wb.createSheet(type);// 创建一个sheet
            //第一行
            Row row0=sheet.createRow(0);
            row0.setHeightInPoints(16);// 设置行高
            Cell cell0=row0.createCell(0);
            cell0.setCellValue(type);//表名
            sheet.addMergedRegion(new CellRangeAddress(0,0,0,head.length - 1));
            CellStyle cellStyleHead = wb.createCellStyle(); //标头样式
            Font font0 = wb.createFont();
            font0.setFontHeightInPoints((short) 12);// 字号
            font0.setBoldweight(Font.BOLDWEIGHT_NORMAL);// 加粗
            cellStyleHead.setFont(font0);
            cellStyleHead.setAlignment(CellStyle.ALIGN_CENTER);// 水平对齐
            cellStyleHead.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
            cell0.setCellStyle(cellStyleHead);
            CellStyle cellStyleHead3 = wb.createCellStyle();
            Font font3= wb.createFont();
            font3.setFontHeightInPoints((short) 12);// 字号
            font3.setBoldweight(Font.BOLDWEIGHT_NORMAL);// 加粗
            cellStyleHead3.setFont(font3);
            cellStyleHead3.setAlignment(CellStyle.ALIGN_CENTER);// 水平对齐
            cellStyleHead3.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
            cellStyleHead3.setFillBackgroundColor(CellStyle.ALIGN_CENTER);
            cellStyleHead3.setBorderTop(CellStyle.BORDER_THIN);
            cellStyleHead3.setBorderRight(CellStyle.BORDER_THIN);
            cellStyleHead3.setBorderBottom(CellStyle.BORDER_THIN);
            cellStyleHead3.setBorderLeft(CellStyle.BORDER_THIN);
            //第四行
            Row row3=sheet.createRow(1);
            for (int k = 0; k < head.length; k++) {
                row3.setHeightInPoints(14);// 设置行高
                sheet.setColumnWidth(k, 60 * 100);
                Cell cell = row3.createCell(k);
                cell.setCellValue(head[k]);
                cell.setCellStyle(cellStyleHead3);
            }

            CellStyle cellStyleBody = wb.createCellStyle();// 表体单元格样式
            cellStyleBody.setAlignment(CellStyle.ALIGN_LEFT);// 水平对齐
            cellStyleBody.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直对齐
            cellStyleBody.setWrapText(true);// 自动换行
            cellStyleBody.setBorderTop(CellStyle.BORDER_THIN);
            cellStyleBody.setBorderRight(CellStyle.BORDER_THIN);
            cellStyleBody.setBorderBottom(CellStyle.BORDER_THIN);
            cellStyleBody.setBorderLeft(CellStyle.BORDER_THIN);
            cellStyleBody.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直
            cellStyleBody.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平

            int beginRowNumber = 2;// 表体开始行
            if(!alertList.isEmpty()){
                for (int i = 0; i < alertList.size(); i++) {
                    Row rowDetail = sheet.createRow(beginRowNumber + i);  //第几行
                    rowDetail.setHeightInPoints(16);// 设置行高
                    Alert alert = alertList.get(i);
                    switch (type) {
                        case "异常信息表":
                            Cell cellbody0 = rowDetail.createCell(0);
                            cellbody0.setCellValue(alert.getNumber());
                            cellbody0.setCellStyle(cellStyleBody);// 设置样式
                            Cell cellbody1 = rowDetail.createCell(1);
                            cellbody1.setCellValue(alert.getType());
                            cellbody1.setCellStyle(cellStyleBody);// 设置样式
                            Cell cellbody2 = rowDetail.createCell(2);
                            cellbody2.setCellValue(alert.getReason());
                            cellbody2.setCellStyle(cellStyleBody);// 设置样式
                            Cell cellbody3 = rowDetail.createCell(3);
                            cellbody3.setCellValue(alert.getTimestring());
                            cellbody3.setCellStyle(cellStyleBody);// 设置样式
                            Cell cellbody4 = rowDetail.createCell(4);
                            cellbody4.setCellValue(alert.getJingdu());
                            cellbody4.setCellStyle(cellStyleBody);// 设置样式
                            Cell cellbody5 = rowDetail.createCell(5);
                            cellbody5.setCellValue(alert.getWeidu());
                            cellbody5.setCellStyle(cellStyleBody);// 设置样式
                            Cell cellbody6 = rowDetail.createCell(6);
                            cellbody6.setCellValue(alert.getState().equals("0") ? "未处理":"已处理");
                            cellbody6.setCellStyle(cellStyleBody);// 设置样式
                            break;
                        case "异常汇总表":
                            cellbody0 = rowDetail.createCell(0);
                            cellbody0.setCellValue(alert.getNumber());
                            cellbody0.setCellStyle(cellStyleBody);// 设置样式
                            cellbody1 = rowDetail.createCell(1);
                            cellbody1.setCellValue(alert.getType());
                            cellbody1.setCellStyle(cellStyleBody);// 设置样式
                            cellbody2 = rowDetail.createCell(2);
                            cellbody2.setCellValue(alert.getReason());
                            cellbody2.setCellStyle(cellStyleBody);// 设置样式
                            cellbody3 = rowDetail.createCell(3);
                            cellbody3.setCellValue(alert.getSum());
                            cellbody3.setCellStyle(cellStyleBody);// 设置样式
                            break;
                        case "异常DTU编号汇总表":
                            cellbody0 = rowDetail.createCell(0);
                            cellbody0.setCellValue(alert.getNumber());
                            cellbody0.setCellStyle(cellStyleBody);// 设置样式
                            cellbody1 = rowDetail.createCell(1);
                            cellbody1.setCellValue(alert.getSum());
                            cellbody1.setCellStyle(cellStyleBody);// 设置样式
                            break;
                        case "异常类型汇总表":
                            cellbody0 = rowDetail.createCell(0);
                            cellbody0.setCellValue(alert.getType());
                            cellbody0.setCellStyle(cellStyleBody);// 设置样式
                            cellbody1 = rowDetail.createCell(1);
                            cellbody1.setCellValue(alert.getSum());
                            cellbody1.setCellStyle(cellStyleBody);// 设置样式
                            break;
                        case "异常原因汇总表":
                            cellbody0 = rowDetail.createCell(0);
                            cellbody0.setCellValue(alert.getReason());
                            cellbody0.setCellStyle(cellStyleBody);// 设置样式
                            cellbody1 = rowDetail.createCell(1);
                            cellbody1.setCellValue(alert.getSum());
                            cellbody1.setCellStyle(cellStyleBody);// 设置样式
                            break;
                        default:
                            break;
                    }
                }
            }

            Row lastRow = sheet.createRow(beginRowNumber + alertList.size());
            lastRow.setHeightInPoints(16);// 设置行高
            Cell lastCell=lastRow.createCell(0);
            User user = CommonUser.getUser();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            lastCell.setCellValue("制表人："+user.getName()+"   制表时间："+simpleDateFormat.format(new Date()));
            //合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
            sheet.addMergedRegion(new CellRangeAddress(alertList.size() + beginRowNumber,alertList.size() + beginRowNumber,0,head.length - 1));
            CellStyle cellStyleLast = wb.createCellStyle(); //标头样式
            Font fontLast = wb.createFont();
            fontLast.setFontHeightInPoints((short) 10);// 字号
            fontLast.setBoldweight(Font.BOLDWEIGHT_NORMAL);// 加粗
            cellStyleLast.setFont(fontLast);
            cellStyleLast.setAlignment(CellStyle.ALIGN_RIGHT);// 水平对齐
            cellStyleLast.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 上下居中
            lastCell.setCellStyle(cellStyleLast);
            wb.write(out);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public int save(Alert record) {
        return alertMapper.insertSelective(record);
    }

    @Override
    public int delete(Alert record) {
        return alertMapper.deleteByPrimaryKey(record.getTid());
    }

    @Override
    public int deletes(List<Alert> records) {
        return 0;
    }

    @Override
    public int update(Alert record) {
        return alertMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public Alert findByTid(String tid) {
        return alertMapper.selectByPrimaryKey(tid);
    }

    @Override
    public List<Alert> findPagingByListTid(List<String> stringList, Integer pageIndex, Integer pageSize) {
        return alertMapper.findPagingByListTid(stringList, pageIndex, pageSize);
    }

//    @Override
//    public List<String> selectAlertBySearch(String number, String userTid) {
//        return alertMapper.selectAlertBySearch(number,userTid);
//    }
//
//    @Override
//    public List<Alert> selectAlertByTid(List<String> list, Integer pageIndex, Integer pageSize) {
//        return alertMapper.selectAlertByTid(list,pageIndex,pageSize);
//    }
//
//    @Override
//    public List<Alert> getNumber(String number) {
//        return alertMapper.getNumber(number);
//    }
//
//    @Override
//    public void updateIsAlert(String tid,String isAlert) {
//        alertMapper.updateIsAlert(tid,isAlert);
//    }
//
//    @Override
//    public List<String> selectAlertHistoricalBySearch(String number) {
//        return alertMapper.selectAlertHistoricalBySearch(number);
//    }
//
//    @Override
//    public List<Alert> selectAlertHistoricalByTid(List<String> list, Integer pageIndex, Integer pageSize) {
//        return alertMapper.selectAlertHistoricalByTid(list,pageIndex,pageSize);
//    }
}
